package com.idp.controller;

import com.idp.config.ServerProperty;
import com.idp.service.CreateCloudLoginUrlSolution;
import com.idp.util.JTRStaticUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.idp.util.JTRStaticUtils.enterpriseSystemLoginURL;

@Controller
public class LoginController {

    @GetMapping("/")
    public String pre(Authentication authentication) {
        return authentication == null ? "pre" : "redirect:/modelSelection";
    }

    @RequestMapping("/login")
    public String login(ModelMap modelMap) {
        return "login";
    }

    @GetMapping("/modelSelection")
    public String modelSelection(HttpServletRequest request, ModelMap modelMap) {
        modelMap.addAttribute("user", request.getRemoteUser());
        return "modelSelection";
    }


    /**
     * 目前IAM用户有: red, green, odder (见 JTRStaticUtils )
     */
    /**
     * 基于saml -- 多用户
     */
    @RequestMapping("/index")
    public String index(Authentication authentication, ModelMap modelMap) {
        // 目前拥有的HUAWEI云配置的IdP账户的名称
        Map<String, String> idpAuthsMap = JTRStaticUtils.getIdpAuthsMap();
        // 是否在华为云认证过的IdP用户. IdP拥有访问华为云的权限
        boolean isIdP = false;
        // 是否拥有admin权限. admin拥有添加用户功能
        boolean isAdmin = false;
        // 访问IAM时,本地作为IdP服务器,提供的IdP的name
        HashSet<String> grantedAuthorities = new HashSet<>();
        for (GrantedAuthority ele : authentication.getAuthorities()) {
            String authority = ele.getAuthority();
            // idp命名与权限命名相同,拥有该命名,则拥有该权限
            if (idpAuthsMap.containsKey(authority)) {
                grantedAuthorities.add(idpAuthsMap.get(authority));
            }
        }
        if (!grantedAuthorities.isEmpty()) {
            isIdP = true;
            if (grantedAuthorities.contains("odder")) {
                isAdmin = true;
            }
        }

        modelMap.addAttribute("isIdP", isIdP);
        modelMap.addAttribute("isAdmin", isAdmin);
        modelMap.addAttribute("grantedAuthorities", grantedAuthorities);
        modelMap.addAttribute("user", authentication);
        return "index";
    }


    /**
     * 基于token
     */
    @GetMapping(value = "/index_token")
    public String indexToken(Authentication authentication, ModelMap modelMap) throws Exception {

        CreateCloudLoginUrlSolution urlSolution = new CreateCloudLoginUrlSolution();
        // 目前拥有的HUAWEI云配置的IdP账户的名称
        Map<String, String> idpAuthsMap = JTRStaticUtils.getIdpAuthsMap();
        // 是否在华为云认证过的IdP用户. IdP拥有访问华为云的权限
        boolean isIdP = false;
        // 是否拥有admin权限. admin拥有添加用户功能
        boolean isAdmin = false;
        // 访问IAM时,本地作为IdP服务器,提供的IdP的name
        HashSet<String> grantedAuthorities = new HashSet<>();
        for (GrantedAuthority ele : authentication.getAuthorities()) {
            String authority = ele.getAuthority();
            // idp命名与权限命名相同,拥有该命名,则拥有该权限
            if (idpAuthsMap.containsKey(authority)) {
                grantedAuthorities.add(idpAuthsMap.get(authority));
            }
        }
        if (!grantedAuthorities.isEmpty()) {
            isIdP = true;
            if (grantedAuthorities.contains("odder")) {
                isAdmin = true;
            }
        }

        Properties keyConfigPro = ServerProperty.getKeyConfigInstance();
        String domainId = keyConfigPro.getProperty("domainId");
        List<Map<String, String>> grantedAuthsList = new ArrayList<>();
        for (String ele: grantedAuthorities) {
            String ak = keyConfigPro.getProperty(ele + "1_AK");
            String sk = keyConfigPro.getProperty(ele + "1_SK");
            if (ak == null || "".equals(ak)) continue;
            String loginUrl = urlSolution.createCloudLoginUrl(enterpriseSystemLoginURL, domainId, ak, sk);
            HashMap<String, String> map = new HashMap<>();
            map.put("auth", ele);
            map.put("loginUrl", loginUrl);
            grantedAuthsList.add(map);
        }

        modelMap.addAttribute("isIdP", isIdP);
        modelMap.addAttribute("isAdmin", isAdmin);
        modelMap.addAttribute("grantedAuthsList", grantedAuthsList);
        modelMap.addAttribute("user", authentication);

        return "index_token";
    }


    /**
     * 基于saml -- 单用户
     */
    @RequestMapping("/index_saml_singleUser")
    public String indexSamlSingleUser(Authentication authentication, ModelMap modelMap) {
        // 目前拥有的HUAWEI云配置的IdP账户的名称
        Map<String, String> idpAuthsMap = JTRStaticUtils.getIdpAuthsMap();
        // 是否在华为云认证过的IdP用户. IdP拥有访问华为云的权限
        boolean isIdP = false;
        // 是否拥有admin权限. admin拥有添加用户功能
        boolean isAdmin = false;
        // 只需要最高权限(数据库中的第一个)
        String grantedAuthority = "";
        for (GrantedAuthority ele : authentication.getAuthorities()) {
            String authority = ele.getAuthority();
            // idp命名与权限命名相同,拥有该命名,则拥有该权限
            if (idpAuthsMap.containsKey(authority)) {
                grantedAuthority = idpAuthsMap.get(authority);
                break;
            }
        }
        if (!"".equals(grantedAuthority)) {
            isIdP = true;
            if ("odder".equals(grantedAuthority)) {
                isAdmin = true;
            }
        }

        modelMap.addAttribute("isIdP", isIdP);
        modelMap.addAttribute("isAdmin", isAdmin);
        modelMap.addAttribute("grantedAuthority", grantedAuthority);
        return "index_saml_singleUser";
    }
}
